package com.koushikdutta.async.middleware;

import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.SimpleMiddleware;
import com.koushikdutta.async.util.Base64;
import com.koushikdutta.async.util.TextUtils;

import java.util.Hashtable;
import java.util.Locale;

/**
 * Created by koush on 2/15/15.
 */
public class BasicAuthMiddleware extends SimpleMiddleware {

    /**
     * insert this using
     *
     * @param client insert this using
     * @return null insert this using
     */
    public static BasicAuthMiddleware add(AsyncHttpClient client) {
        BasicAuthMiddleware ret = new BasicAuthMiddleware();
        client.getMiddleware().add(ret);
        return ret;
    }

    @Override
    public void onRequest(OnRequestData data) {
        super.onRequest(data);
        // do more checking here, since uri may not necessarily be http or have a host, etc.
        String auth = auths.get(data.request.getUri().getDecodedHost());
        if (!TextUtils.isEmpty(auth)){
            data.request.setHeader("Authorization", auth);
        }
    }

    Hashtable<String, String> auths = new Hashtable<String, String>();

    /**
     * Here is a note copy.
     *
     * @param host  Here is a note copy.
     * @param username  Here is a note copy.
     * @param password  Here is a note copy.
     */
    public void setAuthorizationForHost(String host, String username, String password) {
        String auth = "Basic " + Base64.encodeToString(String.format(Locale.ROOT,"%s:%s", username, password).getBytes(), Base64.NO_WRAP);
        auths.put(host, auth);
    }
}
